package com.zthz.douxing.sendmessageservice.handlers

import com.zthz.douxing.PlanTripSaveType
import com.zthz.douxing.SegmentStatus
import com.zthz.douxing.event.UserWillDepartEvent
import com.zthz.douxing.event.UserWillTripJob
import com.zthz.douxing.msg.MessageType
import com.zthz.douxing.sendmessageservice.utils.OrderXingeMessageService
import com.zthz.douxing.util.CommonUtilService
import grails.transaction.Transactional
import org.quartz.JobDataMap
import org.quartz.JobKey
import org.quartz.SimpleTrigger
import org.quartz.impl.triggers.SimpleTriggerImpl

import static org.quartz.JobBuilder.newJob

@Transactional
class PlanTripMessageBeginStatusHanlderService extends AbstractMessageHandlerService{

    @Override
    protected void handle(JobDataMap jobDataMap) {

        UserWillDepartEvent event =  jobDataMap.get("userWillTripEvent")
        if(!event?.getuiId && !event?.xgToken){

            return
        }

        if(event.tripSegment.startTime.getTime() - new Date().getTime()>0){
            Date surplusTime =  event.tripSegment.startTime

            def beginStatusClosure = {JobDataMap jobmap->
                try{
                    UserWillDepartEvent userWillTripEvent = jobDataMap.get("userWillTripEvent")
                    userWillTripEvent.tripSegment.segmentStatus = SegmentStatus.OnPosition
                    OrderXingeMessageService orderXingeMessageService = jobmap.get("orderXingeMessageService")
                    CommonUtilService commonUtilService = jobmap.get("commonUtilService")
                    String resultDesc = "更改状态成功"
                    String msgContent = "更改行程的状态为在OnPosition"
                    if(!commonUtilService.updateTripSegmentStauts(event.tripSegment,null))
                        resultDesc = "更改状态失败"

                    orderXingeMessageService.saveMessageToUserLog(
                            event,msgContent,resultDesc,MessageType.Before3HTripInfo)
                }catch (Exception e){
                    log.debug(e.getMessage(),e.printStackTrace())
                }
            }

            jobDataMap.put(JOBCONTENT_KEY,beginStatusClosure)
            if(event?.tripSegment?.plantrip?.personOwner?.id){
                String beginStatus = redisKeyGenernateService.getRedisKey("beginStatus",event?.tripSegment?.plantrip?.personOwner?.id)
                def jobKey = new JobKey(beginStatus,"UserWillTrip")
                def job = newJob(UserWillTripJob).withIdentity(jobKey).usingJobData(jobDataMap).build()
                SimpleTrigger trigger =
                        new SimpleTriggerImpl("planTripBeginStatusTrigger${surplusTime.format("yyyyMMddHHmm")}",
                                surplusTime, null, 0, 0L)
                quartzScheduler.deleteJob(jobKey)
                addJob(job,trigger)
            }

        }
    }
}
